<template>
    <div class="excel-split-container">
        <div class="page-header">
            <h2>鹰潭制表</h2>
            <p>将Excel文件按照指定条件进行分表处理，适用于鹰潭制表数据格式</p>
        </div>

        <div class="content-wrapper">
            <!-- 文件上传区域 -->
            <div class="upload-section">
                <a-card title="文件上传" class="upload-card">
                    <div class="upload-area">
                        <a-upload-dragger v-model:fileList="fileList" :beforeUpload="beforeUpload" accept=".xlsx,.xls"
                            :multiple="false" @change="handleUploadChange" @remove="handleRemove">
                            <p class="ant-upload-drag-icon">
                                <inbox-outlined />
                            </p>
                            <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
                            <p class="ant-upload-hint">
                                支持 .xlsx 和 .xls 格式的Excel文件
                            </p>
                        </a-upload-dragger>
                    </div>
                </a-card>
            </div>

            <!-- Excel预览区域 -->
            <div class="preview-section" v-if="fileList.length > 0 && excelData.length > 0">
                <a-card title="Excel预览" class="preview-card">
                    <template #extra>
                        <a-space>
                            <a-button @click="showFullPreview" type="primary" size="small">
                                <eye-outlined />
                                全屏预览
                            </a-button>
                            <a-button @click="refreshPreview" size="small">
                                <reload-outlined />
                                刷新
                            </a-button>
                        </a-space>
                    </template>

                    <div class="preview-info">
                        <a-descriptions size="small" :column="4">
                            <a-descriptions-item label="文件名">
                                {{ currentFile?.name }}
                            </a-descriptions-item>
                            <a-descriptions-item label="总行数">
                                {{ excelData.length }}
                            </a-descriptions-item>
                            <a-descriptions-item label="总列数">
                                {{ excelColumns.length }}
                            </a-descriptions-item>
                            <a-descriptions-item label="文件大小">
                                {{ formatFileSize(currentFile?.size) }}
                            </a-descriptions-item>
                        </a-descriptions>
                    </div>

                    <div class="preview-table">
                        <a-table :columns="previewColumns" :data-source="excelData" :pagination="false"
                            :scroll="{ x: 800, y: 400 }" size="small" bordered>
                            <template #bodyCell="{ column, index }">
                                <template v-if="column?.key === 'index'">
                                    {{ index + 1 }}
                                </template>
                            </template>
                        </a-table>
                    </div>
                </a-card>
            </div>

            <!-- 制表配置区域 -->
            <div class="config-section" v-if="fileList.length > 0">
                <a-card title="制表配置" class="config-card">
                    <div class="split-info">
                        <a-alert message="制表说明"
                            description="系统将根据Excel中的'跟进人'列进行数据整理，生成一个包含案件表和分案表的Excel文件，文件名格式为YYYYMMDD(数量).xlsx。"
                            type="info" show-icon style="margin-bottom: 20px" />

                        <a-descriptions size="small" :column="2" bordered>
                            <a-descriptions-item label="数据列">
                                跟进人
                            </a-descriptions-item>
                            <a-descriptions-item label="处理方式">
                                数据整理和格式化
                            </a-descriptions-item>
                            <a-descriptions-item label="检测到的调解员数量" v-if="institutionCount > 0">
                                <span class="highlight">{{ institutionCount }} 个调解员</span>
                            </a-descriptions-item>
                            <a-descriptions-item label="预计生成文件数">
                                <span class="highlight">1 个文件</span>
                            </a-descriptions-item>
                        </a-descriptions>
                    </div>

                    <!-- 模板信息显示 -->
                    <div class="template-info-section">
                        <a-divider orientation="left">
                            <span style="font-weight: 600;">制表模板</span>
                        </a-divider>
                        
                        <a-alert message="使用固定模板" type="info" show-icon style="margin-bottom: 16px" />
                        <a-descriptions size="small" :column="2" bordered>
                            <a-descriptions-item label="模板文件">
                                template/yingtan.xlsx
                            </a-descriptions-item>
                            <a-descriptions-item label="模板类型">
                                鹰潭制表专用模板
                            </a-descriptions-item>
                            <a-descriptions-item label="工作表">
                                案件表、分案表
                            </a-descriptions-item>
                            <a-descriptions-item label="状态">
                                <a-tag color="green">已加载</a-tag>
                            </a-descriptions-item>
                        </a-descriptions>
                    </div>


                    <!-- 操作按钮 -->
                    <div class="action-section">
                        <a-divider orientation="left">
                            <span style="font-weight: 600;">执行操作</span>
                        </a-divider>

                        <div class="action-buttons" style="margin-top: 20px; text-align: center;">
                            <a-space size="large">
                                <a-button type="primary" size="large" @click="handleSplit" :loading="splitting"
                                    :disabled="!canSplit">
                                    <table-outlined />
                                    开始制表
                                </a-button>
                                <a-button size="large" @click="resetConfig">
                                    <reload-outlined />
                                    重置配置
                                </a-button>
                            </a-space>
                            <div v-if="!canSplit" style="margin-top: 12px; color: #ff4d4f; font-size: 14px;">
                                请先上传原始数据Excel文件
                            </div>
                        </div>
                    </div>
                </a-card>
            </div>

            <!-- 制表结果区域 -->
            <div class="result-section" v-if="splitResults.length > 0">
                <a-card title="制表结果" class="result-card">
                    <template #extra>
                        <a-space>
                            <a-button type="primary" size="small" @click="downloadAllFiles" :loading="downloadingAll">
                                <download-outlined />
                                下载文件
                            </a-button>
                            <a-button size="small" @click="refreshResults">
                                <reload-outlined />
                                刷新
                            </a-button>
                        </a-space>
                    </template>

                    <a-table :columns="resultColumns" :data-source="splitResults" :pagination="false" size="small">
                        <template #bodyCell="{ column, record }">
                            <template v-if="column.key === 'action'">
                                <a-space>
                                    <a-button type="link" size="small" @click="downloadFile(record)">
                                        下载
                                    </a-button>
                                    <a-button type="link" size="small" @click="previewFile(record)">
                                        预览
                                    </a-button>
                                </a-space>
                            </template>
                        </template>
                    </a-table>
                </a-card>
            </div>
        </div>

        <!-- 全屏预览Modal -->
        <a-modal v-model:open="fullPreviewVisible" title="Excel全屏预览" :width="'90vw'" :style="{ top: '20px' }"
            :footer="null" :destroyOnClose="true">
            <div class="full-preview-container">
                <div class="full-preview-header">
                    <a-descriptions size="small" :column="4">
                        <a-descriptions-item label="文件名">
                            {{ currentFile?.name }}
                        </a-descriptions-item>
                        <a-descriptions-item label="总行数">
                            {{ excelData.length }}
                        </a-descriptions-item>
                        <a-descriptions-item label="总列数">
                            {{ excelColumns.length }}
                        </a-descriptions-item>
                        <a-descriptions-item label="文件大小">
                            {{ formatFileSize(currentFile?.size) }}
                        </a-descriptions-item>
                    </a-descriptions>
                </div>

                <!-- 按机构分组的选项卡 -->
                <div class="institution-tabs-container">
                    <a-tabs type="card" v-model:activeKey="activeInstitutionTab">
                        <a-tab-pane v-for="institutionName in institutionNames" :key="institutionName"
                            :tab="`${institutionName} (${groupedPreviewData[institutionName]?.length || 0}条)`">
                            <div class="institution-preview-table">
                                <a-table :columns="fullPreviewColumns"
                                    :data-source="groupedPreviewData[institutionName] || []" :pagination="false"
                                    :scroll="{ x: 'max-content', y: '60vh' }" size="small" bordered
                                    :row-key="(record: any) => record.key || Math.random().toString(36).substr(2, 9)">
                                    <template #bodyCell="{ column, index }">
                                        <template v-if="column.key === 'index'">
                                            {{ index + 1 }}
                                        </template>
                                    </template>
                                </a-table>
                            </div>
                        </a-tab-pane>
                    </a-tabs>
                </div>
            </div>
        </a-modal>

        <!-- 机构数据预览Modal -->
        <a-modal v-model:open="previewModalVisible" :title="`${previewInstitutionName} - ${getPreviewTableTitle()}预览`"
            :width="'90vw'" :style="{ top: '20px' }" :footer="null" :destroyOnClose="true">
            <div class="institution-preview-container">
                <div class="institution-preview-header">
                    <a-descriptions size="small" :column="4">
                        <a-descriptions-item label="机构名称">
                            {{ previewInstitutionName }}
                        </a-descriptions-item>
                        <a-descriptions-item label="数据行数">
                            {{ previewInstitutionData.length }}
                        </a-descriptions-item>
                        <a-descriptions-item label="总列数">
                            {{ excelColumns.length }}
                        </a-descriptions-item>
                        <a-descriptions-item label="预览时间">
                            {{ new Date().toLocaleString() }}
                        </a-descriptions-item>
                    </a-descriptions>
                </div>

                <div class="institution-preview-table">
                    <a-table :columns="previewColumns" :data-source="previewInstitutionData" :pagination="false"
                        :scroll="{ x: 'max-content', y: '60vh' }" size="small" bordered
                        :row-key="(record: any) => record.key || Math.random().toString(36).substr(2, 9)">
                        <template #bodyCell="{ column, index }">
                            <template v-if="column.key === 'index'">
                                {{ index + 1 }}
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>
        </a-modal>

        <!-- 模板预览Modal -->
        <a-modal v-model:open="templatePreviewVisible" title="分表模板预览" :width="'90vw'" :style="{ top: '20px' }"
            :footer="null" :destroyOnClose="true">
            <div class="template-preview-container">
                <div class="template-preview-header">
                    <a-descriptions size="small" :column="4">
                        <a-descriptions-item label="模板文件名">
                            {{ templateInfo?.fileName }}
                        </a-descriptions-item>
                        <a-descriptions-item label="工作表数量">
                            {{ templateInfo?.sheetCount }}
                        </a-descriptions-item>
                        <a-descriptions-item label="总列数">
                            {{templateInfo?.worksheets?.reduce((sum, ws) => sum + ws.headers.length, 0) || 0}}
                        </a-descriptions-item>
                        <a-descriptions-item label="总行数">
                            {{templateInfo?.worksheets?.reduce((sum, ws) => sum + ws.dataCount, 0) || 0}}
                        </a-descriptions-item>
                    </a-descriptions>
                </div>

                <!-- 工作表标签页 -->
                <div v-if="templateInfo?.worksheets && templateInfo.worksheets.length > 0"
                    class="template-worksheets-tabs">
                    <a-tabs type="card" @change="handleTemplateTabChange">
                        <a-tab-pane v-for="(worksheet, index) in templateInfo.worksheets" :key="index"
                            :tab="`${worksheet.name} (${worksheet.dataCount}行)`">
                            <div class="worksheet-preview-content">
                                <div class="worksheet-info">
                                    <div class="info-item">
                                        <span class="info-label">表头行：</span>
                                        <span class="info-value">第{{ worksheet.headerRow }}行</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">数据起始行：</span>
                                        <span class="info-value">第{{ worksheet.dataStartRow }}行</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">数据行数：</span>
                                        <span class="info-value">{{ worksheet.dataCount }}行</span>
                                    </div>
                                    <div class="info-item">
                                        <span class="info-label">列数：</span>
                                        <span class="info-value">{{ worksheet.headers.length }}列</span>
                                    </div>
                                </div>

                                <div class="worksheet-preview-table">
                                    <a-table :columns="worksheet.columns" :data-source="worksheet.data"
                                        :pagination="false" :scroll="{ x: 'max-content', y: '50vh' }" size="small"
                                        bordered
                                        :row-key="(record: any) => record.key || Math.random().toString(36).substr(2, 9)">
                                        <template #bodyCell="{ column, index }">
                                            <template v-if="column.key === 'index'">
                                                {{ index + 1 }}
                                            </template>
                                        </template>
                                    </a-table>
                                </div>
                            </div>
                        </a-tab-pane>
                    </a-tabs>
                </div>
            </div>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { InboxOutlined, EyeOutlined, ReloadOutlined, DownloadOutlined, TableOutlined } from '@ant-design/icons-vue';
import type { UploadFile, TableColumnsType } from 'ant-design-vue';
import * as ExcelJS from 'exceljs';
import dayjs from 'dayjs';

// 接口定义
interface SplitConfig {
    bankName?: string; // 银行名称
}

interface SplitResult {
    key: string;
    institutionName: string;
    fileName: string;
    rowCount: number;
    fileSize: string;
    createTime: string;
}

interface ExcelRow {
    [key: string]: any;
}

interface TemplateInfo {
    fileName: string;
    sheetCount: number;
    worksheets: TemplateWorksheet[];
}

interface TemplateWorksheet {
    name: string;
    headers: string[];
    data: ExcelRow[];
    columns: any[];
    headerRow: number;
    dataStartRow: number;
    dataCount: number;
    originalWorksheet?: ExcelJS.Worksheet; // 保存原始工作表引用
}

// 日期格式化函数
const formatCellValue = (value: any, columnName?: string): any => {
    if (value === null || value === undefined) {
        return '';
    }

    // 如果是ExcelJS单元格对象，提取值
    if (value && typeof value === 'object' && 'value' in value) {
        value = value.value;
    }

    // 如果是公式对象，提取计算结果
    if (value && typeof value === 'object' && 'result' in value) {
        value = value.result;
    }

    // 如果是共享公式，提取值
    if (value && typeof value === 'object' && 'formula' in value) {
        // 如果有计算结果，使用计算结果
        if (value.result !== undefined) {
            value = value.result;
        } else {
            // 否则返回空字符串，避免公式错误
            return '';
        }
    }

    // 处理Date对象
    if (value instanceof Date) {
        return dayjs(value).format('YYYY-MM-DD');
    }

    // 处理ExcelJS的Date对象
    if (value && typeof value === 'object' && value.constructor && value.constructor.name === 'Date') {
        return dayjs(value).format('YYYY-MM-DD');
    }

    // 处理时间戳
    if (typeof value === 'number' && value > 1000000000000) {
        return dayjs(value).format('YYYY-MM-DD');
    }

    // 处理字符串格式的日期
    if (typeof value === 'string' && value.includes('GMT')) {
        try {
            const date = new Date(value);
            if (!isNaN(date.getTime())) {
                return dayjs(date).format('YYYY-MM-DD');
            }
        } catch (e) {
            // 如果解析失败，返回原值
        }
    }

    // 确保返回纯值，不包含公式
    const stringValue = value.toString();
    if (stringValue.startsWith('=')) {
        // 如果是公式，返回空字符串
        return '';
    }

    // 检查是否是无效的对象字符串
    if (stringValue === '[object Object]') {
        return '0';
    }

    // 特殊处理0值，确保0值不会被错误处理
    if (value === 0 || value === '0' || stringValue === '0') {
        return '0';
    }

    console.log(columnName, stringValue, 'columnName, stringValue');

    // 处理数值格式化
    return formatNumberValue(stringValue, columnName);
};

// 响应式数据
const fileList = ref<UploadFile[]>([]);
const loadingColumns = ref(false);
const splitting = ref(false);
const availableColumns = ref<string[]>([]);
const splitResults = ref<SplitResult[]>([]);

// Excel预览相关数据
const excelData = ref<ExcelRow[]>([]);
const excelColumns = ref<string[]>([]);
const currentFile = ref<UploadFile | null>(null);
const fullPreviewVisible = ref(false);
const institutionCount = ref(0);

// 按机构分组的数据
const groupedPreviewData = ref<{ [key: string]: ExcelRow[] }>({});
const institutionNames = ref<string[]>([]);
const activeInstitutionTab = ref<string>('');

// 预览相关数据
const previewModalVisible = ref(false);
const previewInstitutionData = ref<ExcelRow[]>([]);
const previewInstitutionName = ref('');

// 批量下载相关数据
const downloadingAll = ref(false);

// 有效列映射（原始列号到过滤后列号的映射）
const validColumnsMap = ref<number[]>([]);

// 模板相关数据
const templateInfo = ref<TemplateInfo | null>(null);
const templatePreviewVisible = ref(false);
const templatePreviewLoading = ref(false);
const templatePreviewData = ref<ExcelRow[]>([]);
const templatePreviewColumns = ref<TableColumnsType<any>>([]);

// 制表配置
const splitConfig = reactive<SplitConfig>({});

// 表格列配置
const resultColumns = [
    {
        title: '文件名',
        dataIndex: 'fileName',
        key: 'fileName',
        ellipsis: true
    },
    {
        title: '行数',
        dataIndex: 'rowCount',
        key: 'rowCount',
        width: 80
    },
    {
        title: '文件大小',
        dataIndex: 'fileSize',
        key: 'fileSize',
        width: 100
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 150
    },
    {
        title: '操作',
        key: 'action',
        width: 120
    }
];

// 预览表格列配置
const previewColumns = computed(() => {
    const columns: TableColumnsType<any> = [];

    // 如果有模板，使用模板的列配置
    if (templateInfo.value && previewInstitutionData.value.length > 0) {
        // 检查预览数据是否包含模板格式的数据
        const firstRow = previewInstitutionData.value[0];
        if (firstRow && firstRow.key && (firstRow.key as string).startsWith('case_')) {
            // 案件表格式
            const caseTemplate = templateInfo.value.worksheets.find(ws => ws.name === '案件表');
            if (caseTemplate) {
                caseTemplate.headers.forEach((header, index) => {
                    const colKey = `col${index + 1}`;
                    // 检查该列是否有数据
                    const hasData = previewInstitutionData.value.some(record =>
                        record[colKey] !== undefined &&
                        record[colKey] !== null &&
                        record[colKey] !== '' &&
                        String(record[colKey]).trim() !== ''
                    );

                    if (hasData) {
                        columns.push({
                            title: header,
                            dataIndex: colKey,
                            key: colKey,
                            width: 150,
                            ellipsis: true,
                            align: 'center',
                            customCell: (record: any) => {
                                // 根据列名判断是否是证件号码列
                                const isIdCardColumn = header && header.includes('证件号码');
                                const cellValue = isIdCardColumn ? formatIdCardValue(record[colKey]) : formatCellValue(record[colKey]);
                                return {
                                    innerHTML: cellValue
                                };
                            }
                        } as any);
                    }
                });
                return columns;
            }
        } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('assignment_')) {
            // 分案表格式
            const assignmentTemplate = templateInfo.value.worksheets.find(ws => ws.name === '分案表');
            if (assignmentTemplate) {
                assignmentTemplate.headers.forEach((header, index) => {
                    const colKey = `col${index + 1}`;
                    // 检查该列是否有数据
                    const hasData = previewInstitutionData.value.some(record =>
                        record[colKey] !== undefined &&
                        record[colKey] !== null &&
                        record[colKey] !== '' &&
                        String(record[colKey]).trim() !== ''
                    );

                    if (hasData) {
                        columns.push({
                            title: header,
                            dataIndex: colKey,
                            key: colKey,
                            width: 150,
                            ellipsis: true,
                            align: 'center',
                            customCell: (record: any) => {
                                const cellValue = formatCellValue(record[colKey]);
                                return {
                                    innerHTML: cellValue
                                };
                            }
                        } as any);
                    }
                });
                return columns;
            }
        } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('financial_')) {
            // 金融资产表格式
            const financialTemplate = templateInfo.value.worksheets.find(ws => ws.name === '金融资产');
            if (financialTemplate) {
                financialTemplate.headers.forEach((header, index) => {
                    const colKey = `col${index + 1}`;
                    // 检查该列是否有数据
                    const hasData = previewInstitutionData.value.some(record =>
                        record[colKey] !== undefined &&
                        record[colKey] !== null &&
                        record[colKey] !== '' &&
                        String(record[colKey]).trim() !== ''
                    );

                    if (hasData) {
                        columns.push({
                            title: header,
                            dataIndex: colKey,
                            key: colKey,
                            width: 150,
                            ellipsis: true,
                            align: 'center',
                            customCell: (record: any) => {
                                // 根据列名判断是否是证件号码列
                                const isIdCardColumn = header && header.includes('证件号码');
                                const cellValue = isIdCardColumn ? formatIdCardValue(record[colKey]) : formatCellValue(record[colKey]);
                                return {
                                    innerHTML: cellValue
                                };
                            }
                        } as any);
                    }
                });
                return columns;
            }
        } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('customer_')) {
            // 客户表格式
            const customerTemplate = templateInfo.value.worksheets.find(ws => ws.name === '客户');
            if (customerTemplate) {
                customerTemplate.headers.forEach((header, index) => {
                    const colKey = `col${index + 1}`;
                    // 检查该列是否有数据
                    const hasData = previewInstitutionData.value.some(record =>
                        record[colKey] !== undefined &&
                        record[colKey] !== null &&
                        record[colKey] !== '' &&
                        String(record[colKey]).trim() !== ''
                    );

                    if (hasData) {
                        columns.push({
                            title: header,
                            dataIndex: colKey,
                            key: colKey,
                            width: 150,
                            ellipsis: true,
                            align: 'center',
                            customCell: (record: any) => {
                                // 根据列名判断是否是证件号码列
                                const isIdCardColumn = header && header.includes('证件号码');
                                const cellValue = isIdCardColumn ? formatIdCardValue(record[colKey]) : formatCellValue(record[colKey]);
                                return {
                                    innerHTML: cellValue
                                };
                            }
                        } as any);
                    }
                });
                return columns;
            }
        }
    }

    // 默认使用原始Excel列配置
    excelColumns.value.forEach((column, index) => {
        // 使用有效列映射找到原始列号
        const originalColNumber = validColumnsMap.value[index];
        const colKey = `col${originalColNumber}`;

        // 检查该列是否有数据（使用excelData而不是previewInstitutionData）
        const hasData = excelData.value.some(record =>
            record[colKey] !== undefined &&
            record[colKey] !== null &&
            record[colKey] !== '' &&
            String(record[colKey]).trim() !== ''
        );

        if (hasData) {
            columns.push({
                title: column,
                dataIndex: colKey,
                key: colKey,
                width: 120,
                ellipsis: true,
                align: 'center',
                customCell: (record: any) => {
                    return {
                        innerHTML: formatCellValue(record[colKey])
                    };
                }
            } as any);
        }
    });

    return columns;
});

// 全屏预览表格列配置
const fullPreviewColumns = computed(() => {
    const columns = [
        {
            title: '序号',
            key: 'index',
            width: 80,
            fixed: 'left'
        }
    ];

    excelColumns.value.forEach((column, index) => {
        // 使用有效列映射找到原始列号
        const originalColNumber = validColumnsMap.value[index];
        const colKey = `col${originalColNumber}`;

        // 检查该列是否有数据（在所有机构的数据中）
        const hasData = Object.values(groupedPreviewData.value).some(institutionData =>
            institutionData.some(record =>
                record[colKey] !== undefined &&
                record[colKey] !== null &&
                record[colKey] !== '' &&
                String(record[colKey]).trim() !== ''
            )
        );

        if (hasData) {
            columns.push({
                title: column,
                dataIndex: colKey,
                key: colKey,
                width: 150,
                ellipsis: true,
                align: 'center',
                customCell: (record: any) => {
                    // 根据列名判断是否是证件号码列
                    const isIdCardColumn = column && column.includes('证件号码');
                    const cellValue = isIdCardColumn ? formatIdCardValue(record[colKey]) : formatCellValue(record[colKey]);
                    return {
                        innerHTML: cellValue
                    };
                }
            } as any);
        }
    });

    return columns;
});


// 计算属性
const canSplit = computed(() => {
    return fileList.value.length > 0 && institutionCount.value > 0;
});


// 文件上传前处理
const beforeUpload = (file: File) => {
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel';

    if (!isExcel) {
        message.error('只能上传Excel文件！');
        return false;
    }

    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
        message.error('文件大小不能超过10MB！');
        return false;
    }

    // 显示确认对话框
    Modal.confirm({
        title: '文件上传确认',
        content: '请确保源文件中的客户姓名、手机号、证件号码列已经调整完毕',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
            // 用户确认后，继续处理文件
            handleUploadChange({ fileList: [{ originFileObj: file }] });
        }
    });

    return false; // 阻止自动上传
};

// 文件上传变化处理
const handleUploadChange = (info: any) => {
    if (info.fileList.length > 0) {
        currentFile.value = info.fileList[0];
        // 解析Excel文件
        parseExcelFile(info.fileList[0].originFileObj);
    }
};

// 移除文件处理
const handleRemove = (_file: UploadFile) => {
    // 清空Excel预览数据
    excelData.value = [];
    excelColumns.value = [];
    availableColumns.value = [];
    splitResults.value = [];
    currentFile.value = null;
    institutionCount.value = 0;
    validColumnsMap.value = [];
    return true;
};

// 解析Excel文件
const parseExcelFile = async (file: File) => {
    loadingColumns.value = true;
    try {
        // 创建文件读取器
        const reader = new FileReader();

        // 读取文件内容
        const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
            reader.onload = (e) => {
                if (e.target?.result instanceof ArrayBuffer) {
                    resolve(e.target.result);
                } else {
                    reject(new Error('无法读取文件内容'));
                }
            };
            reader.onerror = reject;
            reader.readAsArrayBuffer(file);
        });

        // 使用exceljs处理文件
        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(buffer, {
            ignoreNodes: ['sharedStrings']
        });

        // 获取第一个工作表
        const worksheet = workbook.worksheets[0];
        if (!worksheet) {
            throw new Error('Excel文件中没有找到工作表');
        }

        // 解析表头（第一行）
        const allHeaders: string[] = [];
        const headerRow = worksheet.getRow(1);

        if (!headerRow || !headerRow.values || !Array.isArray(headerRow.values)) {
            throw new Error('无法读取Excel表头');
        }

        // 先解析所有表头
        for (let colNumber = 1; colNumber < (headerRow.values as any[]).length; colNumber++) {
            const cellValue = (headerRow.values as any[])[colNumber];
            const headerName = cellValue?.toString()?.trim() || `列${colNumber}`;
            allHeaders[colNumber - 1] = headerName;
        }

        // 解析数据行
        const data: ExcelRow[] = [];
        let dataRowCount = 0;

        worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
            // 跳过表头行
            if (rowNumber === 1) return;

            const rowData: ExcelRow = { key: `row_${rowNumber}` };
            let hasData = false;

            for (let colNumber = 1; colNumber <= allHeaders.length; colNumber++) {
                const cell = row.getCell(colNumber);
                let cellValue = null;

                try {
                    // 尝试获取单元格的值，优先获取计算结果
                    if (cell.value !== null && cell.value !== undefined) {
                        cellValue = cell.value;
                    } else if (cell.result !== null && cell.result !== undefined) {
                        cellValue = cell.result;
                    } else if (cell.text) {
                        cellValue = cell.text;
                    }
                } catch (error) {
                    // 如果获取值失败，跳过这个单元格
                    console.warn(`获取单元格 ${colNumber} 的值失败:`, error);
                    cellValue = null;
                }

                const colKey = `col${colNumber}`;
                // 获取列名，判断是否是证件号码列
                const columnName = allHeaders[colNumber - 1];
                const isIdCardColumn = columnName && columnName.includes('证件号码');

                // 根据列类型选择不同的格式化函数
                if (isIdCardColumn) {
                    // 证件号码使用专门的处理函数，避免数字精度问题
                    rowData[colKey] = formatIdCardValue(cellValue);
                } else {
                    // 其他列使用通用格式化函数
                    rowData[colKey] = formatCellValue(cellValue);
                }

                // 检查是否有非空数据
                if (cellValue !== null && cellValue !== undefined && cellValue !== '') {
                    hasData = true;
                }
            }

            // 只添加有数据的行
            if (hasData) {
                data.push(rowData);
                dataRowCount++;
            }
        });

        console.log(data, '====data excelData');

        // 过滤掉没有数据的列
        const validColumns: number[] = [];
        const validHeaders: string[] = [];
        const tableColumns: TableColumnsType<any> = [];

        // 定义需要隐藏的列（即使有数据也不显示）
        const hiddenColumns = [
            '序号',
            '关注',
            '合同号'
        ];

        allHeaders.forEach((header, index) => {
            const colNumber = index + 1;
            const colKey = `col${colNumber}`;

            // 检查是否是需要隐藏的列
            const isHiddenColumn = hiddenColumns.some(hiddenCol =>
                header.includes(hiddenCol) || hiddenCol.includes(header)
            );

            // 如果是需要隐藏的列，则跳过
            if (isHiddenColumn) {
                console.log(`隐藏列: ${header}`);
                return;
            }

            // 检查这一列是否有非空数据
            const hasData = data.some(row => {
                const value = row[colKey];
                return value !== null && value !== undefined && value !== '' &&
                    value.toString().trim() !== '';
            });

            // 如果有数据，则包含在有效列中
            if (hasData) {
                validColumns.push(colNumber);
                validHeaders.push(header);
                tableColumns.push({
                    title: header,
                    dataIndex: colKey,
                    key: colKey,
                    width: 120,
                    ellipsis: true,
                    align: 'center',
                    customCell: (record: any) => {
                        return {
                            innerHTML: formatCellValue(record[colKey])
                        };
                    }
                });
            }
        });

        console.log('有效列索引:', validColumns);
        console.log('有效列名:', validHeaders);
        console.log('过滤前总列数:', allHeaders.length);
        console.log('过滤后有效列数:', validHeaders.length);

        // 更新数据
        excelColumns.value = validHeaders;
        excelData.value = data;
        availableColumns.value = validHeaders;
        validColumnsMap.value = validColumns;

        // 统计跟进人数量
        const institutionColumnIndex = validHeaders.findIndex(header =>
            header.includes('跟进人')
        );

        console.log(institutionColumnIndex, 'institutionColumnIndex');

        if (institutionColumnIndex !== -1) {
            // 获取原始列号（在allHeaders中的位置）
            const originalColNumber = validColumns[institutionColumnIndex];
            const institutionColumnKey = `col${originalColNumber}`;
            const institutions = new Set();
            console.log(data, 'data');
            data.forEach(row => {
                const institutionName = row[institutionColumnKey];
                console.log(institutionName, 'institutionName');
                if (institutionName && institutionName.toString().trim() !== '') {
                    institutions.add(institutionName.toString().trim());
                }
            });
            console.log(institutions, 'institutions');
            institutionCount.value = institutions.size;
        } else {
            institutionCount.value = 0;
            console.log('未找到"跟进人"列，请检查Excel文件格式', institutionCount.value);
            message.warning('未找到"跟进人"列，请检查Excel文件格式');
        }

        message.success(`Excel文件解析成功，共${validHeaders.length}列（过滤掉${allHeaders.length - validHeaders.length}个空列），${data.length}行数据，检测到${institutionCount.value}个调解员`);
    } catch (error) {
        message.error('Excel文件解析失败');
        console.error('Excel解析错误:', error);
    } finally {
        loadingColumns.value = false;
    }
};

// 格式化文件大小
const formatFileSize = (size?: number) => {
    if (!size) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB'];
    let index = 0;
    let fileSize = size;

    while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024;
        index++;
    }

    return `${fileSize.toFixed(2)} ${units[index]}`;
};

// 显示全屏预览
const showFullPreview = () => {
    // 按跟进人分组数据
    const institutionColumnIndex = excelColumns.value.findIndex(header =>
        header.includes('跟进人')
    );

    if (institutionColumnIndex !== -1) {
        const originalColNumber = validColumnsMap.value[institutionColumnIndex];
        const institutionColumnKey = `col${originalColNumber}`;

        const grouped: { [key: string]: ExcelRow[] } = {};
        const institutions: string[] = [];

        excelData.value.forEach(row => {
            const institutionName = row[institutionColumnKey];
            const key = institutionName ? institutionName.toString().trim() : '未分类';

            if (!grouped[key]) {
                grouped[key] = [];
                institutions.push(key);
            }
            grouped[key].push(row);
        });

        groupedPreviewData.value = grouped;
        institutionNames.value = institutions;
        // 设置默认激活第一个选项卡
        activeInstitutionTab.value = institutions[0] || '';
    } else {
        // 如果没有跟进人列，将所有数据放在一个分组中
        groupedPreviewData.value = { '全部数据': excelData.value };
        institutionNames.value = ['全部数据'];
        activeInstitutionTab.value = '全部数据';
    }

    fullPreviewVisible.value = true;
};

// 刷新预览
const refreshPreview = () => {
    if (currentFile.value?.originFileObj) {
        parseExcelFile(currentFile.value.originFileObj);
    }
};

// 开始制表
const handleSplit = async () => {
    if (!canSplit.value) {
        message.warning('请先上传原始数据Excel文件');
        return;
    }

    splitting.value = true;
    try {
        // 模拟制表处理
        await new Promise(resolve => setTimeout(resolve, 2000));

        // 查找跟进人列
        const institutionColumnIndex = excelColumns.value.findIndex(header =>
            header.includes('跟进人')
        );

        if (institutionColumnIndex === -1) {
            message.error('未找到"跟进人"列，无法进行制表');
            return;
        }

        // 使用有效列映射找到原始列号
        const originalColNumber = validColumnsMap.value[institutionColumnIndex];
        const institutionColumnKey = `col${originalColNumber}`;

        // 统计调解员数量
        const institutions = new Set();
        excelData.value.forEach(row => {
            const institutionName = row[institutionColumnKey];
            if (institutionName && institutionName.toString().trim() !== '') {
                institutions.add(institutionName.toString().trim());
            }
        });

        // 生成制表结果
        const today = new Date();
        const dateStr = today.getFullYear().toString() +
            (today.getMonth() + 1).toString().padStart(2, '0') +
            today.getDate().toString().padStart(2, '0');
        
        const fileName = `${dateStr}（${excelData.value.length}）.xlsx`;
        
        const result: SplitResult = {
            key: 'result_1',
            institutionName: '全部数据',
            fileName: fileName,
            rowCount: excelData.value.length,
            fileSize: formatFileSize(excelData.value.length * 100), // 估算文件大小
            createTime: new Date().toLocaleString()
        };

        splitResults.value = [result];

        // 显示制表成功消息
        message.success(`制表处理完成！生成文件：${fileName}，包含${excelData.value.length}条数据，${institutions.size}个调解员`);
    } catch (error) {
        message.error('制表处理失败');
        console.error('制表处理错误:', error);
    } finally {
        splitting.value = false;
    }
};

// 重置配置
const resetConfig = () => {
    splitResults.value = [];
    splitConfig.bankName = '';
};

// 组件挂载时初始化
onMounted(async () => {
    console.log('鹰潭制表组件已挂载');
    // 加载固定模板
    await loadFixedTemplate();
});

// 加载固定模板
const loadFixedTemplate = async () => {
    try {
        // 这里应该从服务器加载固定模板文件
        // 暂时创建一个模拟的模板信息
        templateInfo.value = {
            fileName: 'template/yingtan.xlsx',
            sheetCount: 2,
            worksheets: [
                {
                    name: '案件表',
                    headerRow: 1,
                    dataStartRow: 2,
                    dataCount: 0,
                    headers: ['*合同编号', '*合同名称', '*申请人名称', '*案由', '*借款平台', '*被申请人名称', '*身份证号码', '*手机号码1', '*逾期开始日期', '*计算截止日期', '*逾期天数', '*诉请总金额'],
                    data: [],
                    columns: [],
                    originalWorksheet: undefined
                },
                {
                    name: '分案表',
                    headerRow: 1,
                    dataStartRow: 2,
                    dataCount: 0,
                    headers: ['', '合同编号', '', '调解员姓名', '调解员ID'],
                    data: [],
                    columns: [],
                    originalWorksheet: undefined
                }
            ]
        };
        console.log('固定模板加载成功');
    } catch (error) {
        console.error('加载固定模板失败:', error);
        message.error('加载固定模板失败');
    }
};

// 下载文件
const downloadFile = async (record: SplitResult) => {
    try {
        // 使用全部数据
        const allData = excelData.value;

        if (allData.length === 0) {
            message.error('未找到数据');
            return;
        }

        // 创建新的工作簿
        const workbook = new ExcelJS.Workbook();

        // 使用模板格式生成完整的工作簿
        if (templateInfo.value) {
            await generateWorkbookWithTemplate(workbook, allData, templateInfo.value, '全部数据');
        } else {
            message.error('未找到制表模板，无法进行制表操作');
            return;
        }

        // 生成Excel文件，禁用共享公式
        const buffer = await workbook.xlsx.writeBuffer({
            useSharedStrings: false,
            useStyles: true
        });

        // 创建下载链接
        const blob = new Blob([buffer], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = record.fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        message.success(`文件 ${record.fileName} 下载成功`);
    } catch (error) {
        console.error('下载文件失败:', error);
        message.error('下载文件失败');
    }
};


// 使用模板格式生成完整的工作簿
const generateWorkbookWithTemplate = async (workbook: ExcelJS.Workbook, institutionData: ExcelRow[], template: TemplateInfo, _institutionName: string) => {
    // 创建两个工作表：案件表、分案表
    const caseWorksheet = workbook.addWorksheet('案件表');
    const assignmentWorksheet = workbook.addWorksheet('分案表');

    // 处理案件表
    if (template.worksheets && template.worksheets.length > 0) {
        const caseTemplate = template.worksheets.find(ws => ws.name === '案件表');
        if (caseTemplate) {
            await fillCaseWorksheetWithTemplate(caseWorksheet, institutionData, caseTemplate);
        }
    }

    // 处理分案表
    if (template.worksheets && template.worksheets.length > 1) {
        const assignmentTemplate = template.worksheets.find(ws => ws.name === '分案表');
        if (assignmentTemplate) {
            await fillAssignmentWorksheetWithTemplate(assignmentWorksheet, institutionData, assignmentTemplate);
        }
    }

    // 自动调整所有工作表的列宽（仅对没有预设宽度的列）
    [caseWorksheet, assignmentWorksheet].forEach(worksheet => {
        for (let i = 0; i < worksheet.columns.length; i++) {
            const column = worksheet.columns[i];
            if (column && column.eachCell && !column.width) {
                let maxLength = 0;
                column.eachCell({ includeEmpty: true }, (cell) => {
                    const columnLength = cell.value ? cell.value.toString().length : 10;
                    if (columnLength > maxLength) {
                        maxLength = columnLength;
                    }
                });
                column.width = Math.min(maxLength + 2, 50);
            }
        }
    });
};

// 调解员ID映射
const mediatorIdMapping: { [key: string]: string } = {
    '王建立': 'tjy002224',
    '王亚男': 'tjy002974',
    '冯晓鑫': 'tjy002235',
    '廖英见': 'tjy002222'
};

// 填充案件表数据
const fillCaseWorksheetWithTemplate = async (worksheet: ExcelJS.Worksheet, institutionData: ExcelRow[], template: TemplateWorksheet) => {
    // 如果有原始工作表，先复制样式
    if (template.originalWorksheet) {
        copyWorksheetStyle(template.originalWorksheet, worksheet);
    }

    // 添加数据行
    institutionData.forEach((rowData, rowIndex) => {
        const dataRow = worksheet.getRow(2 + rowIndex); // 从第2行开始填充数据

        // 案件表列映射：A-L列
        const columnMappings = [
            { templateCol: 'A', sourceCol: '借款编号' },
            { templateCol: 'B', sourceCol: '现金贷款合同' },
            { templateCol: 'C', sourceCol: '南宁天思商务服务有限公司' },
            { templateCol: 'D', sourceCol: '借款合同纠纷' },
            { templateCol: 'E', sourceCol: '产品名称' },
            { templateCol: 'F', sourceCol: '客户姓名' },
            { templateCol: 'G', sourceCol: '证件号' },
            { templateCol: 'H', sourceCol: '客户手机号' },
            { templateCol: 'I', sourceCol: '放款日期' },
            { templateCol: 'J', sourceCol: '还款日期' },
            { templateCol: 'K', sourceCol: '逾期天数' },
            { templateCol: 'L', sourceCol: '借款余额' }
        ];

        columnMappings.forEach((mapping, index) => {
            const cell = dataRow.getCell(index + 1); // A列是第1列
            let cellValue = '';

            if (mapping.sourceCol === '现金贷款合同') {
                cellValue = '现金贷款合同';
            } else if (mapping.sourceCol === '南宁天思商务服务有限公司') {
                cellValue = '南宁天思商务服务有限公司';
            } else if (mapping.sourceCol === '借款合同纠纷') {
                cellValue = '借款合同纠纷';
            } else {
                // 从源数据中获取值
                const sourceValue = rowData[getColumnKey(mapping.sourceCol)];
                cellValue = formatCellValue(sourceValue);
            }

            cell.value = cellValue;
        });
    });
};

// 填充分案表数据
const fillAssignmentWorksheetWithTemplate = async (worksheet: ExcelJS.Worksheet, institutionData: ExcelRow[], template: TemplateWorksheet) => {
    // 如果有原始工作表，先复制样式
    if (template.originalWorksheet) {
        copyWorksheetStyle(template.originalWorksheet, worksheet);
    }

    // 添加数据行
    institutionData.forEach((rowData, rowIndex) => {
        const dataRow = worksheet.getRow(2 + rowIndex); // 从第2行开始填充数据

        // 分案表列映射：B、D、E列
        // B列：合同编号（借款编号）
        const contractNumber = formatCellValue(rowData[getColumnKey('借款编号')]);
        dataRow.getCell(2).value = contractNumber; // B列

        // D列：调解员姓名（跟进人）
        const mediatorName = formatCellValue(rowData[getColumnKey('跟进人')]);
        dataRow.getCell(4).value = mediatorName; // D列

        // E列：调解员ID（根据调解员姓名映射）
        const mediatorId = mediatorIdMapping[mediatorName] || '';
        dataRow.getCell(5).value = mediatorId; // E列
    });
};

// 使用模板格式填充单个工作表（已弃用，保留以兼容）
const fillWorksheetWithTemplate = async (_worksheet: ExcelJS.Worksheet, _institutionData: ExcelRow[], _template: TemplateWorksheet, _headerRowNum: number, _dataStartRowNum: number, _institutionName: string) => {
    // 此函数已弃用，不再使用
};


// 获取列键的辅助函数
const getColumnKey = (columnName: string): string => {
    console.log(`查找列键: ${columnName}`);
    console.log('可用列名:', excelColumns.value);

    const columnIndex = excelColumns.value.findIndex(header =>
        header.includes(columnName) || columnName.includes(header)
    );

    console.log(`找到的列索引: ${columnIndex}`);

    if (columnIndex !== -1) {
        const originalColNumber = validColumnsMap.value[columnIndex];
        const colKey = `col${originalColNumber}`;
        console.log(`返回列键: ${colKey}`);
        return colKey;
    }

    console.warn(`未找到列: ${columnName}`);
    return '';
};

// 格式化证件号码，确保原封不动保存
const formatIdCardValue = (value: any): string => {
    if (value === null || value === undefined) {
        return '';
    }

    // 如果是ExcelJS单元格对象，提取值
    if (value && typeof value === 'object' && 'value' in value) {
        value = value.value;
    }

    // 如果是公式对象，提取计算结果
    if (value && typeof value === 'object' && 'result' in value) {
        value = value.result;
    }

    // 如果是共享公式，提取值
    if (value && typeof value === 'object' && 'formula' in value) {
        if (value.result !== undefined) {
            value = value.result;
        } else {
            return '';
        }
    }
    const valueString = String(value).trim();
    console.log(valueString, '====valueString');
    // 直接转换为字符串，不进行任何数字处理
    return valueString;
};

// 格式化数字值，处理浮点数精度问题
const formatNumberValue = (value: any, columnName?: string): string => {
    console.log('formatNumberValue 输入:', value, typeof value);

    if (value === null || value === undefined) {
        return '';
    }

    // 如果已经是字符串且为数字格式，直接处理
    if (typeof value === 'string') {
        const trimmed = value.trim();
        if (trimmed === '') {
            return '';
        }
        if (trimmed === '0') {
            return '0';
        }
        // 检查是否是无效的对象字符串
        if (trimmed === '[object Object]') {
            // 对于『当前拖欠利息（元）』列，返回"0"
            if (columnName === '当前拖欠利息（元）') {
                return '0';
            }
            return '';
        }
        const numValue = parseFloat(trimmed);
        if (!isNaN(numValue)) {
            if (Number.isInteger(numValue)) {
                return numValue.toString();
            }
            const formatted = numValue.toFixed(2);
            return parseFloat(formatted).toString();
        }
        return trimmed;
    }

    // 如果是数字类型
    if (typeof value === 'number') {
        if (value === 0) {
            return '0';
        }
        if (Number.isInteger(value)) {
            return value.toString();
        }
        const formatted = value.toFixed(2);
        return parseFloat(formatted).toString();
    }

    // 如果是对象，尝试提取数值
    if (value && typeof value === 'object') {
        // 检查是否是ExcelJS单元格对象
        if ('result' in value) {
            return formatNumberValue(value.result, columnName);
        }
        if ('value' in value) {
            return formatNumberValue(value.value, columnName);
        }
        if ('text' in value) {
            return formatNumberValue(value.text, columnName);
        }
        if ('numValue' in value) {
            return formatNumberValue(value.numValue, columnName);
        }
        // 如果无法提取有效值，对于利息列返回"0"
        if (columnName === '当前拖欠利息（元）') {
            return '0';
        }
        return '';
    }

    // 其他情况，尝试转换为字符串
    try {
        const stringValue = value.toString();
        if (stringValue === '[object Object]') {
            // 对于利息列，返回"0"
            if (columnName === '当前拖欠利息（元）') {
                return '0';
            }
            return '';
        }
        return formatNumberValue(stringValue, columnName);
    } catch (error) {
        // 对于利息列，即使转换失败也返回"0"
        if (columnName === '当前拖欠利息（元）') {
            return '0';
        }
        return '';
    }
};

// 获取公式计算结果值的辅助函数（已弃用，保留以兼容）
const getFormulaValue = (_rowData: ExcelRow, _columnName: string): string => {
    return '';
};

// 创建空的分案关系工作表（已弃用，保留以兼容）
const createEmptyRelationshipWorksheet = async (_worksheet: ExcelJS.Worksheet) => {
    // 此函数已弃用，不再使用
};


// 预览文件
const previewFile = async (record: SplitResult) => {
    try {
        // 使用全部数据
        const allData = excelData.value;

        if (allData.length === 0) {
            message.error('未找到数据');
            return;
        }

        // 生成模板格式的预览数据
        if (templateInfo.value) {
            await generateTemplatePreviewData(allData, '全部数据');
        } else {
            message.error('未找到制表模板，无法预览数据');
            return;
        }

        previewInstitutionName.value = '全部数据';
        previewModalVisible.value = true;

    } catch (error) {
        console.error('预览文件失败:', error);
        message.error('预览文件失败');
    }
};

// 生成模板格式的预览数据
const generateTemplatePreviewData = async (institutionData: ExcelRow[], institutionName: string) => {
    // 默认显示案件表数据
    const caseTemplate = templateInfo.value?.worksheets.find(ws => ws.name === '案件表');
    if (caseTemplate) {
        const caseData = await generateCasePreviewData(institutionData, institutionName, caseTemplate);
        previewInstitutionData.value = caseData;
    } else {
        // 如果没有案件表，显示分案表
        const assignmentTemplate = templateInfo.value?.worksheets.find(ws => ws.name === '分案表');
        if (assignmentTemplate) {
            const assignmentData = await generateAssignmentPreviewData(institutionData, institutionName, assignmentTemplate);
            previewInstitutionData.value = assignmentData;
        }
    }
};

// 生成案件表预览数据
const generateCasePreviewData = async (institutionData: ExcelRow[], _institutionName: string, _template: TemplateWorksheet) => {
    const previewData: ExcelRow[] = [];

    institutionData.forEach((rowData, rowIndex) => {
        const previewRow: ExcelRow = { key: `case_${rowIndex}` };

        // 案件表列映射：A-L列
        const columnMappings = [
            { templateCol: 'A', sourceCol: '借款编号', displayName: '*合同编号' },
            { templateCol: 'B', sourceCol: '现金贷款合同', displayName: '*合同名称' },
            { templateCol: 'C', sourceCol: '南宁天思商务服务有限公司', displayName: '*申请人名称' },
            { templateCol: 'D', sourceCol: '借款合同纠纷', displayName: '*案由' },
            { templateCol: 'E', sourceCol: '产品名称', displayName: '*借款平台' },
            { templateCol: 'F', sourceCol: '客户姓名', displayName: '*被申请人名称' },
            { templateCol: 'G', sourceCol: '证件号', displayName: '*身份证号码' },
            { templateCol: 'H', sourceCol: '客户手机号', displayName: '*手机号码1' },
            { templateCol: 'I', sourceCol: '放款日期', displayName: '*逾期开始日期' },
            { templateCol: 'J', sourceCol: '还款日期', displayName: '*计算截止日期' },
            { templateCol: 'K', sourceCol: '逾期天数', displayName: '*逾期天数' },
            { templateCol: 'L', sourceCol: '借款余额', displayName: '*诉请总金额' }
        ];

        columnMappings.forEach((mapping, index) => {
            const colKey = `col${index + 1}`;
            let cellValue = '';

            if (mapping.sourceCol === '现金贷款合同') {
                cellValue = '现金贷款合同';
            } else if (mapping.sourceCol === '南宁天思商务服务有限公司') {
                cellValue = '南宁天思商务服务有限公司';
            } else if (mapping.sourceCol === '借款合同纠纷') {
                cellValue = '借款合同纠纷';
            } else {
                // 从源数据中获取值
                const sourceValue = rowData[getColumnKey(mapping.sourceCol)];
                cellValue = formatCellValue(sourceValue);
            }

            previewRow[colKey] = cellValue;
        });

        previewData.push(previewRow);
    });

    return previewData;
};

// 生成分案表预览数据
const generateAssignmentPreviewData = async (institutionData: ExcelRow[], _institutionName: string, _template: TemplateWorksheet) => {
    const previewData: ExcelRow[] = [];

    institutionData.forEach((rowData, rowIndex) => {
        const previewRow: ExcelRow = { key: `assignment_${rowIndex}` };

        // 分案表列映射：B、D、E列
        const contractNumber = formatCellValue(rowData[getColumnKey('借款编号')]);
        const mediatorName = formatCellValue(rowData[getColumnKey('跟进人')]);
        const mediatorId = mediatorIdMapping[mediatorName] || '';

        previewRow['col1'] = ''; // A列空
        previewRow['col2'] = contractNumber; // B列：合同编号
        previewRow['col3'] = ''; // C列空
        previewRow['col4'] = mediatorName; // D列：调解员姓名
        previewRow['col5'] = mediatorId; // E列：调解员ID

        previewData.push(previewRow);
    });

    return previewData;
};

// 生成金融资产表预览数据（已弃用，保留以兼容）
const generateFinancialAssetPreviewData = async (_institutionData: ExcelRow[], _institutionName: string, _template: TemplateWorksheet) => {
    return [];
};

// 生成客户表预览数据（已弃用，保留以兼容）
const generateCustomerPreviewData = async (_institutionData: ExcelRow[], _institutionName: string, _template: TemplateWorksheet) => {
    return [];
};

// 复制模板样式到新工作表
const copyWorksheetStyle = (sourceWorksheet: ExcelJS.Worksheet, targetWorksheet: ExcelJS.Worksheet) => {
    // 复制列宽
    sourceWorksheet.columns.forEach((sourceCol, index) => {
        if (sourceCol.width) {
            targetWorksheet.getColumn(index + 1).width = sourceCol.width;
        }
    });

    // 复制行高
    sourceWorksheet.eachRow({ includeEmpty: true }, (sourceRow, rowNumber) => {
        if (sourceRow.height) {
            targetWorksheet.getRow(rowNumber).height = sourceRow.height;
        }
    });

    // 复制单元格样式和合并
    sourceWorksheet.eachRow({ includeEmpty: true }, (sourceRow, rowNumber) => {
        const targetRow = targetWorksheet.getRow(rowNumber);

        sourceRow.eachCell({ includeEmpty: true }, (sourceCell, colNumber) => {
            const targetCell = targetRow.getCell(colNumber);

            // 复制单元格样式
            if (sourceCell.style) {
                targetCell.style = JSON.parse(JSON.stringify(sourceCell.style));
            }

            // 复制单元格值（如果存在）
            if (sourceCell.value !== null && sourceCell.value !== undefined) {
                targetCell.value = sourceCell.value;
            }
        });
    });

    // 复制合并单元格
    sourceWorksheet.model.merges?.forEach(merge => {
        targetWorksheet.mergeCells(merge);
    });

    // 复制数据验证（如果支持）
    try {
        const sourceDataValidations = (sourceWorksheet as any).dataValidations;
        if (sourceDataValidations) {
            // 检查是否是数组或可迭代对象
            if (Array.isArray(sourceDataValidations)) {
                sourceDataValidations.forEach((validation: any) => {
                    (targetWorksheet as any).dataValidations.add(validation);
                });
            } else if (sourceDataValidations.forEach) {
                sourceDataValidations.forEach((validation: any) => {
                    (targetWorksheet as any).dataValidations.add(validation);
                });
            } else if (sourceDataValidations.values) {
                // 如果是Map或Set类型
                for (const validation of sourceDataValidations.values()) {
                    (targetWorksheet as any).dataValidations.add(validation);
                }
            }
        }
    } catch (error) {
        console.warn('复制数据验证失败:', error);
    }

    // 复制条件格式（如果支持）
    try {
        const sourceConditionalFormattings = (sourceWorksheet as any).conditionalFormattings;
        if (sourceConditionalFormattings) {
            // 检查是否是数组或可迭代对象
            if (Array.isArray(sourceConditionalFormattings)) {
                sourceConditionalFormattings.forEach((conditionalFormatting: any) => {
                    (targetWorksheet as any).conditionalFormattings.add(conditionalFormatting);
                });
            } else if (sourceConditionalFormattings.forEach) {
                sourceConditionalFormattings.forEach((conditionalFormatting: any) => {
                    (targetWorksheet as any).conditionalFormattings.add(conditionalFormatting);
                });
            } else if (sourceConditionalFormattings.values) {
                // 如果是Map或Set类型
                for (const conditionalFormatting of sourceConditionalFormattings.values()) {
                    (targetWorksheet as any).conditionalFormattings.add(conditionalFormatting);
                }
            }
        }
    } catch (error) {
        console.warn('复制条件格式失败:', error);
    }

    // 复制批注（注释）
    try {
        copyComments(sourceWorksheet, targetWorksheet);
    } catch (error) {
        console.warn('复制批注失败:', error);
    }
};

// 复制批注（注释）的专用函数
const copyComments = (sourceWorksheet: ExcelJS.Worksheet, targetWorksheet: ExcelJS.Worksheet) => {
    sourceWorksheet.eachRow({ includeEmpty: true }, (sourceRow, rowNumber) => {
        sourceRow.eachCell({ includeEmpty: true }, (sourceCell, colNumber) => {
            if (sourceCell.note) {
                const targetCell = targetWorksheet.getCell(rowNumber, colNumber);

                try {
                    // 深度复制批注对象
                    const noteData = JSON.parse(JSON.stringify(sourceCell.note));

                    // 创建新的批注对象
                    const newNote: any = {};

                    // 复制基本属性（使用类型断言）
                    const sourceNote = sourceCell.note as any;
                    if (sourceNote.texts) {
                        newNote.texts = sourceNote.texts;
                    }
                    if (sourceNote.margins) {
                        newNote.margins = sourceNote.margins;
                    }
                    if (sourceNote.size) {
                        newNote.size = sourceNote.size;
                    }
                    if (sourceNote.editAs) {
                        newNote.editAs = sourceNote.editAs;
                    }

                    // 复制其他可能的属性
                    Object.keys(noteData).forEach(key => {
                        if (!['texts', 'margins', 'size', 'editAs'].includes(key)) {
                            newNote[key] = noteData[key];
                        }
                    });

                    // 设置批注
                    targetCell.note = newNote;

                } catch (noteError) {
                    console.warn(`复制单元格 ${rowNumber},${colNumber} 的批注失败:`, noteError);

                    // 如果深度复制失败，尝试简单复制
                    try {
                        const sourceNote = sourceCell.note as any;
                        targetCell.note = {
                            texts: sourceNote.texts || [],
                            margins: sourceNote.margins || {},
                            editAs: sourceNote.editAs || 'oneCell',
                            ...(sourceNote.size && { size: sourceNote.size })
                        } as any;
                    } catch (simpleError) {
                        console.warn(`简单复制批注也失败:`, simpleError);
                    }
                }
            }
        });
    });
};

// 带样式的金融资产表数据填充（已弃用，保留以兼容）
const fillFinancialAssetDataWithStyle = async (_worksheet: ExcelJS.Worksheet, _institutionData: ExcelRow[], _template: TemplateWorksheet, _headerRowNum: number, _dataStartRowNum: number, _institutionName: string) => {
    // 此函数已弃用，不再使用
};

// 带样式的客户表数据填充（已弃用，保留以兼容）
const fillCustomerDataWithStyle = async (_worksheet: ExcelJS.Worksheet, _institutionData: ExcelRow[], _template: TemplateWorksheet, _headerRowNum: number, _dataStartRowNum: number, _institutionName: string) => {
    // 此函数已弃用，不再使用
};

// 获取预览表标题
const getPreviewTableTitle = () => {
    if (previewInstitutionData.value.length > 0) {
        const firstRow = previewInstitutionData.value[0];
        if (firstRow && firstRow.key && (firstRow.key as string).startsWith('case_')) {
            return '案件表';
        } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('assignment_')) {
            return '分案表';
        } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('financial_')) {
            return '金融资产表';
        } else if (firstRow && firstRow.key && (firstRow.key as string).startsWith('customer_')) {
            return '客户表';
        }
    }
    return '数据';
};

// 批量下载所有文件
const downloadAllFiles = async () => {
    if (splitResults.value.length === 0) {
        message.warning('没有可下载的文件');
        return;
    }

    downloadingAll.value = true;
    try {
        // 鹰潭制表只生成一个文件，直接下载
        await downloadFile(splitResults.value[0]);
        message.success('文件下载成功');
    } catch (error) {
        console.error('下载失败:', error);
        message.error('下载失败');
    } finally {
        downloadingAll.value = false;
    }
};

// 刷新结果
const refreshResults = () => {
    // 重新执行分表逻辑
    if (canSplit.value) {
        handleSplit();
    } else {
        message.warning('请先完成分表配置');
    }
};


// 定义预期的模板工作表格式
const EXPECTED_TEMPLATE_SHEETS = [
    {
        name: '案件表',
        headerRow: 1,
        dataStartRow: 2
    },
    {
        name: '分案表',
        headerRow: 1,
        dataStartRow: 2
    }
];

// 解析模板文件
const parseTemplateFile = async (file: File) => {
    templatePreviewLoading.value = true;
    try {
        // 创建文件读取器
        const reader = new FileReader();

        // 读取文件内容
        const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {
            reader.onload = (e) => {
                if (e.target?.result instanceof ArrayBuffer) {
                    resolve(e.target.result);
                } else {
                    reject(new Error('无法读取模板文件内容'));
                }
            };
            reader.onerror = reject;
            reader.readAsArrayBuffer(file);
        });

        // 使用exceljs处理文件
        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(buffer, {
            ignoreNodes: ['sharedStrings']
        });

        // 处理每个工作表
        const processedWorksheets: TemplateWorksheet[] = [];
        let totalDataCount = 0;

        workbook.worksheets.forEach((worksheet, index) => {
            const expectedSheet = EXPECTED_TEMPLATE_SHEETS[index];

            // 解析表头（根据预期格式）
            const headers: string[] = [];
            const headerRowNumber = expectedSheet?.headerRow || 1;
            const dataStartRowNumber = expectedSheet?.dataStartRow || 2;
            const headerRow = worksheet.getRow(headerRowNumber);

            if (!headerRow || !headerRow.values || !Array.isArray(headerRow.values)) {
                return; // 跳过无效的工作表
            }

            // 解析所有表头
            for (let colNumber = 1; colNumber < (headerRow.values as any[]).length; colNumber++) {
                const cellValue = (headerRow.values as any[])[colNumber];
                const headerName = cellValue?.toString()?.trim() || `列${colNumber}`;
                headers[colNumber - 1] = headerName;
            }

            // 解析数据行（最多显示前10行作为预览）
            const data: ExcelRow[] = [];
            let rowCount = 0;

            worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
                // 跳过表头行之前的所有行
                if (rowNumber < dataStartRowNumber) return;

                // 只解析前10行数据用于预览
                if (rowCount >= 10) return;

                const rowData: ExcelRow = { key: `row_${rowNumber}` };
                let hasData = false;

                for (let colNumber = 1; colNumber <= headers.length; colNumber++) {
                    const cell = row.getCell(colNumber);
                    let cellValue = null;

                    try {
                        if (cell.value !== null && cell.value !== undefined) {
                            cellValue = cell.value;
                        } else if (cell.result !== null && cell.result !== undefined) {
                            cellValue = cell.result;
                        } else if (cell.text) {
                            cellValue = cell.text;
                        }
                    } catch (error) {
                        console.warn(`获取模板单元格 ${colNumber} 的值失败:`, error);
                        cellValue = null;
                    }

                    const colKey = `col${colNumber}`;
                    // 获取列名，判断是否是证件号码列
                    const columnName = headers[colNumber - 1];
                    const isIdCardColumn = columnName && columnName.includes('证件号码');

                    // 根据列类型选择不同的格式化函数
                    if (isIdCardColumn) {
                        // 证件号码使用专门的处理函数，避免数字精度问题
                        rowData[colKey] = cellValue;
                    } else {
                        // 其他列使用通用格式化函数
                        rowData[colKey] = formatCellValue(cellValue);
                    }

                    if (cellValue !== null && cellValue !== undefined && cellValue !== '') {
                        hasData = true;
                    }
                }

                if (hasData) {
                    data.push(rowData);
                    rowCount++;
                }
            });

            console.log(data, '====data');

            // 生成表格列配置
            const columns: TableColumnsType<any> = [];

            headers.forEach((header, colIndex) => {
                const colNumber = colIndex + 1;
                const colKey = `col${colNumber}`;
                columns.push({
                    title: header,
                    dataIndex: colKey,
                    key: colKey,
                    width: 120,
                    ellipsis: true,
                    align: 'center',
                    customCell: (record: any) => {
                        return {
                            innerHTML: formatCellValue(record[colKey])
                        };
                    }
                });
            });

            // 创建工作表对象
            const worksheetData: TemplateWorksheet = {
                name: worksheet.name,
                headers: headers,
                data: data,
                columns: columns,
                headerRow: headerRowNumber,
                dataStartRow: dataStartRowNumber,
                dataCount: rowCount,
                originalWorksheet: worksheet // 保存原始工作表引用
            };

            processedWorksheets.push(worksheetData);
            totalDataCount += rowCount;
        });

        // 更新模板信息
        templateInfo.value = {
            fileName: file.name,
            sheetCount: workbook.worksheets.length,
            worksheets: processedWorksheets
        };

        // 更新预览数据（显示第一个工作表的数据）
        if (processedWorksheets.length > 0) {
            templatePreviewData.value = processedWorksheets[0].data;
            templatePreviewColumns.value = processedWorksheets[0].columns;
        }

        message.success(`模板文件解析成功！检测到 ${processedWorksheets.length} 个有效工作表，共 ${totalDataCount} 行数据`);
    } catch (error) {
        message.error('模板文件解析失败');
        console.error('模板解析错误:', error);
    } finally {
        templatePreviewLoading.value = false;
    }
};

// 预览模板
const previewTemplate = () => {
    if (templateInfo.value) {
        templatePreviewVisible.value = true;
    }
};


// 处理模板标签页切换
const handleTemplateTabChange = (key: string) => {
    if (templateInfo.value?.worksheets) {
        const index = parseInt(key);
        const worksheet = templateInfo.value.worksheets[index];
        if (worksheet) {
            templatePreviewData.value = worksheet.data;
            templatePreviewColumns.value = worksheet.columns;
        }
    }
};
</script>

<style scoped>
.excel-split-container {
    padding: 0;
}

.page-header {
    margin-bottom: 24px;
}

.page-header h2 {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: #262626;
}

.page-header p {
    margin: 0;
    color: #8c8c8c;
    font-size: 14px;
}

.content-wrapper {
    display: flex;
    flex-direction: column;
    gap: 24px;
}

.upload-section,
.config-section,
.result-section {
    width: 100%;
}

.upload-card,
.config-card,
.result-card {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border-radius: 8px;
}

.upload-area {
    padding: 20px;
}

.ant-upload-drag {
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    background: #fafafa;
    transition: all 0.3s;
}

.ant-upload-drag:hover {
    border-color: #1890ff;
    background: #f0f8ff;
}

.ant-upload-drag-icon {
    font-size: 48px;
    color: #1890ff;
    margin-bottom: 16px;
}

.ant-upload-text {
    font-size: 16px;
    color: #262626;
    margin-bottom: 8px;
}

.ant-upload-hint {
    font-size: 14px;
    color: #8c8c8c;
    margin: 0;
}

/* 预览区域样式 */
.preview-section {
    width: 100%;
}

.preview-card {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border-radius: 8px;
}

/* 分表信息样式 */
.split-info {
    margin-bottom: 20px;
}

.highlight {
    color: #1890ff;
    font-weight: 600;
}

.preview-info {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 6px;
}

.preview-table {
    margin-top: 16px;
    max-height: 500px;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
}

/* 全屏预览样式 */
.full-preview-container {
    max-height: 80vh;
    overflow: hidden;
}

.full-preview-header {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 6px;
}

.full-preview-table {
    max-height: 70vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
}

/* 机构选项卡样式 */
.institution-tabs-container {
    margin-top: 16px;
}

.institution-preview-table {
    max-height: 60vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    margin-top: 16px;
}

.institution-tabs-container .ant-tabs-card>.ant-tabs-nav .ant-tabs-tab {
    background: #f5f5f5;
    border: 1px solid #d9d9d9;
    border-bottom: none;
    border-radius: 6px 6px 0 0;
    margin-right: 4px;
}

.institution-tabs-container .ant-tabs-card>.ant-tabs-nav .ant-tabs-tab-active {
    background: #fff;
    border-bottom: 1px solid #fff;
    color: #1890ff;
}

.institution-tabs-container .ant-tabs-card>.ant-tabs-content {
    border: 1px solid #d9d9d9;
    border-top: none;
    border-radius: 0 0 6px 6px;
    padding: 16px;
    background: #fff;
}

/* 机构预览样式 */
.institution-preview-container {
    max-height: 80vh;
    overflow: hidden;
}

.institution-preview-header {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #f0f8ff;
    border-radius: 6px;
    border-left: 4px solid #1890ff;
}

.institution-preview-table {
    max-height: 60vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
}

/* 表格样式优化 */
.ant-table-thead>tr>th {
    background-color: #f5f5f5;
    font-weight: 600;
    text-align: center;
}

.ant-table-tbody>tr>td {
    text-align: center;
    padding: 8px 12px;
}

.ant-table-tbody>tr:hover>td {
    background-color: #f0f8ff;
}

/* 滚动条样式优化 */
.preview-table::-webkit-scrollbar,
.full-preview-table::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.preview-table::-webkit-scrollbar-track,
.full-preview-table::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.preview-table::-webkit-scrollbar-thumb,
.full-preview-table::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.preview-table::-webkit-scrollbar-thumb:hover,
.full-preview-table::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 模板上传区域样式 */
.template-upload-section {
    margin-top: 24px;
}

/* 银行名称区域样式 */
.bank-name-section {
    margin-top: 24px;
}

.template-upload-area {
    padding: 16px;
}

.template-upload-area .ant-upload-drag {
    border: 2px dashed #52c41a;
    border-radius: 8px;
    background: #f6ffed;
    transition: all 0.3s;
}

.template-upload-area .ant-upload-drag:hover {
    border-color: #389e0d;
    background: #f0f9e8;
}

.template-upload-area .ant-upload-drag-icon {
    font-size: 36px;
    color: #52c41a;
    margin-bottom: 12px;
}

.template-upload-area .ant-upload-text {
    font-size: 14px;
    color: #262626;
    margin-bottom: 6px;
}

.template-upload-area .ant-upload-hint {
    font-size: 12px;
    color: #8c8c8c;
    margin: 0;
}

.template-info {
    margin-top: 16px;
}

.template-actions {
    display: flex;
    justify-content: flex-end;
}

/* 模板预览样式 */
.template-preview-container {
    max-height: 80vh;
    overflow: hidden;
}

.template-preview-header {
    margin-bottom: 16px;
    padding: 16px;
    background-color: #f6ffed;
    border-radius: 6px;
    border-left: 4px solid #52c41a;
}

.template-preview-table {
    max-height: 60vh;
    overflow: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
}

/* 模板工作表样式 */
.template-worksheets {
    margin-top: 16px;
}

.template-worksheets-tabs {
    margin-top: 16px;
}

.worksheet-preview {
    padding: 16px 0;
}

.worksheet-preview-content {
    padding: 16px 0;
}

.worksheet-info {
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 20px;
    display: flex;
    gap: 24px;
    flex-wrap: wrap;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.info-label {
    color: #666;
    font-size: 14px;
}

.info-value {
    color: #1a1a1a;
    font-weight: 500;
    font-size: 14px;
}

.worksheet-preview-table {
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    overflow: hidden;
    margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .content-wrapper {
        gap: 16px;
    }

    .page-header h2 {
        font-size: 20px;
    }

    .upload-area {
        padding: 16px;
    }

    .template-upload-area {
        padding: 12px;
    }

    .preview-info .ant-descriptions-item-label,
    .full-preview-header .ant-descriptions-item-label,
    .template-preview-header .ant-descriptions-item-label {
        font-size: 12px;
    }

    .preview-info .ant-descriptions-item-content,
    .full-preview-header .ant-descriptions-item-content,
    .template-preview-header .ant-descriptions-item-content {
        font-size: 12px;
    }
}
</style>